using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using ETestIT.Core;
using ETestIT.Core.DataInterfaces;
using SharpArch.Core.PersistenceSupport;

namespace ETestIT.Web.Controllers
{
    public class LoginController : Controller
    {
        private readonly IUserRepository _userRepository;

        public LoginController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string userName, string password, string ReturnUrl)
        {
#if DEBUG
            userName = "admin";
            password = "admin";
#endif

            if(IsValidLoginArgument(userName, password))
            {
                if (_userRepository.LogIn(userName, password) != null)
                    RedirectFromLoginPage(userName, ReturnUrl);
                else
                    ViewData["LoginFaild"] = "Login faild! Make sure you have entered the right user name and password!";
            }

            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return View("Login");
        }

        private void RedirectFromLoginPage(string userName, string ReturnUrl)
        {
            FormsAuthentication.SetAuthCookie(userName, false);

            if (!string.IsNullOrEmpty(ReturnUrl))
                Response.Redirect(ReturnUrl);
            else
                Response.Redirect(FormsAuthentication.DefaultUrl);
        }

        private bool IsValidLoginArgument(string userName, string password)
        {
            return !(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password));
        }
    }
}